package com.hanson.utils;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.hanson.common.exception.RateLimitException;
import com.hanson.common.pojo.City;
import org.apache.commons.lang3.StringUtils;
import org.lionsoul.ip2region.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;

import javax.servlet.http.HttpServletRequest;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.regex.Pattern;

/**
 * @CLassName IpUtils
 * @Description ip工具
 * @Author hanson
 * @Date 2020/11/26 14:28
 **/
public class IpUtils {
    private final static Logger log =LoggerFactory.getLogger(IpUtils.class);

    private final static String ANY_HOST = "0.0.0.0";
    private final static String LOCAL_HOST = "127.0.0.1";
    private final static String IPV6 = "0:0:0:0:0:0:0:1";
    private final static Pattern IP_PATTERN = Pattern.compile("\\d{1,3}(\\.\\d{1,3}){3,5}$");

    private static volatile InetAddress LOCAL_ADDRESS= null;
    /**
     * Mob官网注册申请即可
     */
    private final static String APPKEY = "31b5df5f63d3c";
    /**
     * Mob全国天气预报接口
     */
    private final static String GET_WEATHER="http://apicloud.mob.com/v1/weather/ip?key="+ APPKEY +"&ip=";

    //ip非法检测匹配正则
    private final static String REGEX = ".*[a-zA-Z]+.*";
    private final static Pattern p = Pattern.compile(REGEX);

    //接入离线ip解析
    private static String dbPath = "";
    private static DbConfig dbConfig;
    //解析文件直接载入内存
    private volatile static byte[] ip2Region;
    //内网ip
    private final static List<Long> intranetIpSection = new ArrayList<>();
    static {
        String os = System.getProperty("os.name");
        boolean isWindows = os.toLowerCase().contains("windows");
        boolean isMac = os.toLowerCase().contains("mac");
        boolean isLinux = os.toLowerCase().contains("linux");
        //linux or mac
        if (!isWindows){
            dbPath = "/project/ip2region/ip2region.db";
        }
        //windows
        if (StringUtils.isBlank(dbPath)){
            ClassPathResource resource = new ClassPathResource("ip2region/ip2region.db");
            try {
                dbPath = resource.getFile().getAbsolutePath();
            } catch (IOException e) {
                log.error(e.getMessage(),e);
            }
        }

        try {
            if (StringUtils.isNotBlank(dbPath)){
                ip2Region = new FileInputStream(dbPath).readAllBytes();
                dbConfig = new DbConfig();
            }
        } catch (DbMakerConfigException | IOException e) {
            log.error(e.getMessage(),e);
        }
        //内网ip缓存
        final String[] sectionStr = {
                "0.0.0.0","0.255.255.255",
                "10.0.0.0","10.255.255.255",
                "100.64.0.0","100.122.255.255",
                "100.123.0.0","100.127.255.255",
                "127.0.0.0","127.255.255.255",
                "169.254.0.0","169.254.255.255",
                "172.16.0.0","172.31.255.255",
                "192.0.0.0","192.0.0.255",
                "192.0.2.0","192.0.2.255",
                "192.88.99.0","192.88.99.255",
                "192.168.0.0","192.168.255.255",
                "198.18.0.0","198.19.255.255",
                "198.51.100.0","198.51.100.255",
                "203.0.113.0","203.0.113.255",
                "224.0.0.0","255.255.255.255"};
        for (String s : sectionStr) {
            intranetIpSection.add(Util.ip2long(s));
        }
    }

    private IpUtils(){}

    /**
     * get ip
     * @return
     */
    public static String getIp(){
        InetAddress address = getAddress();
        if (address == null){
            return null;
        }
        return address.getHostAddress();
    }

    /**
     * get address
     * @return
     */
    private static InetAddress getAddress() {
        if (LOCAL_ADDRESS != null){
            return LOCAL_ADDRESS;
        }
        InetAddress localAddress = getFirstValidAddress();
        LOCAL_ADDRESS = localAddress;
        return localAddress;
    }


    /**
     * get first valid address
     * @return
     */
    private static InetAddress getFirstValidAddress() {
        InetAddress localAddress = null;
        try {
            localAddress = InetAddress.getLocalHost();
            if (isValidAddress(localAddress)) {
                return localAddress;
            }
        } catch (Throwable e) {
            log.error("Failed to retrying ip address, " + e.getMessage(), e);
        }
        try {
            Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
            if (interfaces != null) {
                while (interfaces.hasMoreElements()) {
                    try {
                        NetworkInterface network = interfaces.nextElement();
                        Enumeration<InetAddress> addresses = network.getInetAddresses();
                        if (addresses != null) {
                            while (addresses.hasMoreElements()) {
                                try {
                                    InetAddress address = addresses.nextElement();
                                    if (isValidAddress(address)) {
                                        return address;
                                    }
                                } catch (Throwable e) {
                                    log.error("Failed to retrying ip address, " + e.getMessage(), e);
                                }
                            }
                        }
                    } catch (Throwable e) {
                        log.error("Failed to retrying ip address, " + e.getMessage(), e);
                    }
                }
            }
        } catch (Throwable e) {
            log.error("Failed to retrying ip address, " + e.getMessage(), e);
        }
        log.error("Could not get local host ip address, will use 127.0.0.1 instead.");
        return localAddress;
    }

    /**
     * valid address
     * @param address
     * @return
     */
    private static boolean isValidAddress(InetAddress address) {
        if (address == null || address.isLoopbackAddress()) {
            return false;
        }
        String name = address.getHostAddress();
        return (name != null
                && ! ANY_HOST.equals(name)
                && ! LOCAL_HOST.equals(name)
                && IP_PATTERN.matcher(name).matches());
    }

    /**
     * 获取客户端IP地址
     * @param request 请求
     * @return
     */
    public static String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        //检查是否x-forwarded-for等非标准请求头伪造
        isIntranetIp(ip);
        //直接获取tcp连接协议里的ip
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
            if (LOCAL_HOST.equals(ip) || IPV6.equals(ip)) {
                //根据网卡取本机配置的IP
                InetAddress inet = null;
                try {
                    inet = InetAddress.getLocalHost();
                    ip = inet.getHostAddress();
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                }
            }
        }
        // 对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
        if (ip != null && ip.length() > 15) {
            if (ip.indexOf(",") > 0) {
                ip = ip.substring(0, ip.indexOf(","));
            }
        }
//        log.info("request.getRemoteAddr=" + ip);
        if (StringUtils.isBlank(ip)){
            log.info("get request ip error! ip is null!");
        }
        return ip;
    }

    /**
     * 检测ip是否包含非法字符,优先级为：敏感字符>英文字符>字符串长度，含有返回true，否则false
     * @param ip 检测的ip字符串
     * @return true or false
     */
    public static boolean checkIpIllegalCharacter(String ip){
        if (StringUtils.isBlank(ip)){
            return false;
        }
        //检测是否包含敏感字符串jndi，dns等
        String lip = ip.toLowerCase();
        if (lip.contains("jndi") || lip.contains("dns")){
            return true;
        }
        //检测ip里面是否包含a-z,A-Z字符集
        boolean res = p.matcher(ip).matches();
        if (!res){
            if (ip.length() > 16){
                //长度非法
                return true;
            }
        }
        //检查是否ipv4格式

        return res;
    }

    /**
     * 剔除ip字段里面的英文字母
     * @param ip
     * @return
     */
    public static String excludeIpLetters(String ip){
        if (StringUtils.isBlank(ip)){
            return null;
        }
        char[] chars = ip.toCharArray();
        List<Character> characters = new ArrayList<>();
        for (char aChar : chars) {
            if (aChar >= 'A' && aChar <= 'z'){
                continue;
            }
            characters.add(aChar);
        }
        if (CollectionUtil.isEmpty(characters)){
            return null;
        }
        char[] achars = new char[characters.size()];
        for (int i = 0; i < characters.size(); i++) {
            achars[i] = characters.get(i);
        }
        return new String(achars);
    }


    /**
     * 获取IP返回地理信息
     * @param city 城市对象
     * @return
     */
    public static String getIpString(City city){
        if(null != city){
            if (!BeanUtil.isEmpty(city)){
                return (StringUtils.isNotBlank(city.getNation()) ?
                        city.getNation() : "")
                        + (StringUtils.isNotBlank(city.getRegion()) ?
                        " "  + city.getRegion() : "")
                        + (StringUtils.isNotBlank(city.getCity()) ?
                        " "  + city.getCity() : "");
            }
            return "-";
        }
        return null;
    }

    //接入离线ip解析lion soul

    public static String getIpOffLine(String ip){
        if (dbConfig == null || StringUtils.isBlank(dbPath)){
            return null;
        }
        try {
            DbSearcher dbSearcher = new DbSearcher(dbConfig, ip2Region);
            DataBlock dataBlock = dbSearcher.memorySearch(ip);
            if (dataBlock == null){
                return null;
            }
            String region = dataBlock.getRegion();
            if (StringUtils.isBlank(region)) return "error";
            return region.replace("|0", "").replaceAll("\\|"," ");
        } catch (IOException e) {
            log.error(e.getMessage(),e);
        }
        return "未知";
    }

    /***
     *
     * 获取有效ip
     *
     * @params: [originIp]
     * @param: originIp  源ip字符串
     * @return: {@link String}
     * @since: 2022/10/13
     **/
    public static String getEffectiveIp(String originIp){
        boolean ipIllegalCharacter = IpUtils.checkIpIllegalCharacter(originIp);
        if (ipIllegalCharacter){
            if (StringUtils.isNotBlank(originIp) && originIp.length() > 16){
                originIp = originIp.substring(0,16);
            }
            String msg = originIp;
            originIp = IpUtils.excludeIpLetters(originIp);
            if (StringUtils.isBlank(originIp)){
                throw new RateLimitException("非法IP注入，已拦截，IP注部分信息：" + originIp);
            }
        }
        return StringUtils.isBlank(originIp) ? "0.0.0.0" : originIp;
    }

    /***
     *
     * 是否内网ip
     *
     * @params: [ip]
     * @param: ip   ip字符串
     * @return: {@link boolean} 是返回true，否则false
     * @since: 2022/10/13
     **/
    public static boolean isIntranetIp(String ip){
        String effectiveIp = getEffectiveIp(ip);
        long ip2long = Util.ip2long(effectiveIp);
        if ("0.0.0.0".equals(effectiveIp)){
            return true;
        }
        if (ip2long == 0){
            log.error("ip非法！ip：{}",ip);
            throw new IllegalArgumentException("ip非法！ip：{" + ip + "}");
        }
        int size = intranetIpSection.size();
        for (int i = 0; i < size; i += 2) {
            if (ip2long >= intranetIpSection.get(i) && ip2long <= intranetIpSection.get(i + 1)){
                //内网ip
                return true;
            }
        }
        return false;
    }
}
